package nii.game.mobileserio.action_game;

import java.io.InputStream;
import java.util.ArrayList;

import javax.microedition.khronos.opengles.GL10;

import nii.game.mobileserio.class_static.ControlStatic;
import nii.game.mobileserio.database.Database;
import nii.game.mobileserio.enemy.Coin;
import nii.game.mobileserio.enemy.Enemy;
import nii.game.mobileserio.enemy.Mushroom;
import nii.game.mobileserio.maps.Maps;
import nii.game.mobileserio.player.Player;
import nii.game.mobileserio.player.StatusPlayer;
import nii.game.mobileserio.sound.MusicBg;
import nii.game.mobileserio.sound.SoundEffect;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.BoundCamera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener;
import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperties;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTile;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTileProperty;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMap;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.entity.util.FPSCounter;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.extension.input.touch.controller.MultiTouch;
import org.anddev.andengine.extension.input.touch.controller.MultiTouchController;
import org.anddev.andengine.extension.input.touch.exception.MultiTouchException;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;

public class MainGameActivity extends BaseGameActivity {
 
	//===============================================|| Declarations ||===================================================//
	
	// Size ===================================
	private static final int WIDTH = 480;
	private static final int HEIGHT = 320;

	// Scene, Camera, HUD =====================
	private Scene myScene;
	private BoundCamera myCamera;
	private HUD hud = new HUD();
	
	// Database ===============================
	private Database db = new Database(this);
	
	// Objects ================================
	private Player mario; 
	private Enemy[] arr_enemy; 
	private Coin[] arr_coin;
	private Mushroom[] arr_mushroom;
	
	// Text ====================================
	private Font mScoreFont;
	private BitmapTextureAtlas mScoreFontTexture;

	// Audio ===================================
	private MusicBg musicBg;
	private SoundEffect sound_ResetPlayer;
	private SoundEffect sound_EnemyDie;
	private SoundEffect sound_GetCoin;
	int volume = 10;
	
	
	// Map =====================================
	private TMXTiledMap mTMXTiledMap; //Map
	private TMXLayer VatCanTMXLayer; //Vật cản
	private TMXLayer FlagTMXLayer; //Flag
	private TMXLayer HosauTMXLayer; //Hố sâu
	private TMXLayer CanEnemyTMXLayer;//Enemy
	private String TEN_MAPS = ""; 	//Tên map
	
	
	// Turn Left-Right Region ===============================
	private DigitalOnScreenControl mDigitalOnScreenControl;
	private BitmapTextureAtlas mOnScreenControlTexture;
	private TextureRegion mOnScreenControlBaseTextureRegion;
	private TextureRegion mOnScreenControlKnobTextureRegion;
	
	// Jump Region ==========================================
	private BitmapTextureAtlas jump_texture;
	private TextureRegion jump_region;
	private Sprite jump_sprite;
	
	// Heart ================================================
    private BitmapTextureAtlas heart_texture;
	private TextureRegion heart_region;
	private Sprite heart_sprite;
	private ChangeableText heart_text;
	 
	// Physical Parameters ====================
	private int is_Jump = 0;
	private int GRAVITY = 3;
	private static final int VEC_Y = 6;
	private float BOTTOM_Y = 0;
	private static final int MAX_HIGH = 105;
	
	// Status Game ============================
	private boolean OVERGAME = false;
    private boolean WIN = false;
     
    // Score, Level, Time =====================
    private int SCORE = 0;
	private ChangeableText score_text; 
	private int LEVEL = 1;//Map 1
	private ChangeableText level_text;
	private int TIME = 0;//Time of curLevel
	private ChangeableText time_text;
    
	// Life ===================================
    private int HEART = 3;
    private float COUNT_ENEMY = 0;
    private float COUNT_COIN = 0;
    private float COUNT_MUSHROOM = 0;
	private String FILE_MAPS = "";
 
	//================================================|| onLoadEngine Function ||==============================================//
	
	public Engine onLoadEngine() {
		Bundle b = getIntent().getExtras();
		if (b != null){
			LEVEL = b.getInt("LEVEL");
			SCORE = b.getInt("SCORE");
			HEART = b.getInt("HEART");
			TEN_MAPS = b.getString("TEN_MAPS");
			FILE_MAPS = b.getString("FILE_MAPS"); 
			TIME = b.getInt("TIME");
		}
		else{
			LEVEL = 1;
			SCORE = 0;
			HEART = 3;
			TEN_MAPS = "maps_1.tmx";
			FILE_MAPS = "maps_1.txt";
			TIME = 2500;
		}
 
		// Khởi tạo vùng hiển thị 480*320 ====================================
		this.myCamera = new BoundCamera(0, 0, WIDTH, HEIGHT);
		
		EngineOptions eo = new EngineOptions(true, ScreenOrientation.LANDSCAPE, // Horizontal || Vertical -> ScreenOrientation.PORTRAIT
				new RatioResolutionPolicy(WIDTH, HEIGHT), myCamera);
		eo.getTouchOptions().setRunOnUpdateThread(true);
		eo.getRenderOptions().disableExtensionVertexBufferObjects();
		eo.setNeedsMusic(true);
		eo.setNeedsSound(true);
		Engine engine = new Engine(eo);
		
		// Testing isMultitouch Device ? =====================================
		try{
    		if (MultiTouch.isSupported(this)){
    			engine.setTouchController(new MultiTouchController());
    			if (MultiTouch.isSupportedDistinct(this)){
    			} 
    			else {
    			}
    		} 
    		else {
    		}
    	} 
		catch (final MultiTouchException e) {
    	}
		
		return engine;
	}
	
	//===============================================|| onLoadResource Function ||=============================================//
	
	public void onLoadResources() {
		
		//Load texts ==========================================================================
		this.mScoreFontTexture = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT);	 
		FontFactory.setAssetBasePath("font/");
		this.mScoreFont = FontFactory.createFromAsset(this.mScoreFontTexture, this, "Droid.ttf", 14, true, Color.WHITE); 
		this.mEngine.getTextureManager().loadTextures(mScoreFontTexture );
		this.mEngine.getFontManager().loadFonts(mScoreFont );
	
		// Load pictures =======================================================================
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		
					//--------------------- Control Region ---------------------\\
		this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 256,	TextureOptions.DEFAULT);
		this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mOnScreenControlTexture, this, "control.png", 5, 0);
		this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mOnScreenControlTexture, this, "control_center.png", 128, 0);
		this.mEngine.getTextureManager().loadTextures(this.mOnScreenControlTexture);
		
					//--------------------- Jump Region ------------------------\\
		jump_texture = new BitmapTextureAtlas(256, 256, TextureOptions.DEFAULT);
		jump_region = BitmapTextureAtlasTextureRegionFactory.createFromAsset(jump_texture, this, "control_up.png", 0, 0);
		mEngine.getTextureManager().loadTexture(jump_texture);
 	
		// Load hearts ===========================================================================
		heart_texture = new BitmapTextureAtlas(64, 64, TextureOptions.DEFAULT);
		heart_region = BitmapTextureAtlasTextureRegionFactory.createFromAsset(heart_texture, this, "heart.png", 0, 0);
		mEngine.getTextureManager().loadTexture(heart_texture);		
		
		// Load tài nguyên khác
		loadResources();
	}

	//===============================================|| onLoadScene Function ||=============================================//
	
	public Scene onLoadScene() 
	{
		//=======================================================================
		myScene = new Scene();
		this.mEngine.registerUpdateHandler(new FPSLogger());
		myScene.setOnAreaTouchTraversalFrontToBack(); // HÀM HỖ TRỢ MULTITOUCH
		myScene.setTouchAreaBindingEnabled(true);// HÀM HỖ TRỢ MULTITOUCH

		// FPS counter begins ===================================================
        final FPSCounter fpsCounter = new FPSCounter();
        this.mEngine.registerUpdateHandler(fpsCounter);
 
		// Load maps ============================================================
		mTMXTiledMap = Maps.getTMXTiledMap(mEngine, this, TEN_MAPS);
		ArrayList<TMXLayer> mapLayers = mTMXTiledMap.getTMXLayers();
		for (TMXLayer layer : mapLayers) 
		{
			if (layer.getName().equals("vatcan")   ){
				VatCanTMXLayer = layer; //NẾU LÀ VẬT CẢN THÌ KHÔNG CHO HIỂN THỊ
				System.out.println("vat can");
				continue;
			}
			if (layer.getName().equals("win_flag") ){
				FlagTMXLayer = layer; //NẾU LÀ VẬT CẢN THÌ KHÔNG CHO HIỂN THỊ
				System.out.println("win flag ");
				continue;
			}
			if (layer.getName().equals("hosau") ){
				HosauTMXLayer = layer; //NẾU LÀ VẬT CẢN THÌ KHÔNG CHO HIỂN THỊ
				System.out.println("ho sau ");
				continue;
			}
			if (layer.getName().equals("can_enemy")){
				CanEnemyTMXLayer = layer;
				System.out.println("can enemy");
				continue;
			}
			myScene.attachChild(layer);
		}
		final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
		
		// BoundCamera ==========================================================
		this.myCamera.setBounds(0, tmxLayer.getWidth(), 0, tmxLayer.getHeight());
		this.myCamera.setBoundsEnabled(true);

		
		// Load Player ==========================================================
		loadScenes(); 
		
		// Camera di chuyển theo Player
		myCamera.setChaseEntity(mario.getAnimatedSprite());
		
		// Hearts =============================================================================================
		heart_sprite = new Sprite(130, 10, heart_region);
		hud.attachChild(heart_sprite); 
		heart_text = new ChangeableText(this.heart_sprite.getX() + 30,10,this.mScoreFont,String.valueOf(mario.getHeart()),2);
        hud.attachChild(heart_text);
		
        // Texts ==============================================================================================
        hud.attachChild(new Text(10, 10, mScoreFont, "Score"));
 		hud.attachChild(new Text(250, 10, mScoreFont, "Time"));
 		hud.attachChild(new Text(370, 10, mScoreFont, "Scene"));
		
        // Scores ==============================================================================================
        score_text = new ChangeableText(60, 10, mScoreFont, String.valueOf(SCORE), 3);
		hud.attachChild(score_text);
		
		// Levels ==============================================================================================
		level_text = new ChangeableText(430, 10, mScoreFont, String.valueOf(LEVEL), 2);
		hud.attachChild(level_text);
		
		// Time ================================================================================================
        time_text = new ChangeableText(290, 10, mScoreFont, String.valueOf(TIME), 4);
        hud.attachChild(time_text);
        
        // Frame Per Second ====================================================================================
        final ChangeableText fpsText = new ChangeableText(10, 35, this.mScoreFont, "FPS:", "FPS: XXXXX".length());
        hud.attachChild(fpsText);
        myScene.registerUpdateHandler(new TimerHandler(1 / 20.0f, true, new ITimerCallback() {
            public void onTimePassed(final TimerHandler pTimerHandler) {
                    fpsText.setText("FPS: " + fpsCounter.getFPS());
            }
        }));
        
 		// TOUCHING EVENTS ==============================================================================================
		jump_sprite = new Sprite(WIDTH - jump_region.getWidth() - 50, HEIGHT - jump_region.getHeight() - 15, jump_region)
		{
			// Chạm vào Sprite
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
					final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				if (is_Jump == 0)
					switch (pSceneTouchEvent.getAction()) {
					case TouchEvent.ACTION_DOWN:
						is_Jump = 1;
						return true;
					}
				return false;
			}
		};
		
		// Hiệu chỉnh sprite
		jump_sprite.setAlpha(0.8f);
		jump_sprite.setScale(1.5f);
		
		// Add vào HUD
		hud.attachChild(jump_sprite);
		hud.registerTouchArea(jump_sprite);
		 
		
		// CONTROL PLAYERT =================================================================================================
		mDigitalOnScreenControl = new DigitalOnScreenControl(4, HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight() + 40,
		this.myCamera, this.mOnScreenControlBaseTextureRegion, 
		this.mOnScreenControlKnobTextureRegion, 0.1f, new IOnScreenControlListener() 
		{
			float pX = 0, pY = 0;
			public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) 
			{
				 // SANG PHẢI 
				if (pValueX > 0) 
				{
					if (is_Jump == 0)
						mario.setStatusPlayer(StatusPlayer.MOVE_RIGHT);
					else
					{
						if (mario.getStatusMario() == StatusPlayer.MOVE_UP_LEFT)
							mario.setStatusPlayer(StatusPlayer.MOVE_UP_RIGHT);
					}
					pX = mario.getX() + mario.getWidth();
					pY = mario.getY() + mario.getHeight() + 1;
					
				} 
				
				// SANG TRÁI
				else if (pValueX < 0) 
				{ 
					if (is_Jump == 0)
						mario.setStatusPlayer(StatusPlayer.MOVE_LEFT);
					else
					{
						if (mario.getStatusMario() == StatusPlayer.MOVE_UP_RIGHT)
							mario.setStatusPlayer(StatusPlayer.MOVE_UP_LEFT);
					}
					pX = mario.getX();
					pY = mario.getY() + mario.getHeight() + 1;
					
				} else if (pValueY == -1) {

				} else if (pValueY == 1) {

				}
				
				// ĐỨNG YÊN
				else 
				{ 
					if (mario.getStatusMario() == StatusPlayer.MOVE_RIGHT || mario.getStatusMario() == StatusPlayer.MOVE_UP_RIGHT)
						mario.setStatusPlayer(StatusPlayer.UN_MOVE_RIGHT);
					else if (mario.getStatusMario() == StatusPlayer.MOVE_LEFT || mario.getStatusMario() == StatusPlayer.MOVE_UP_LEFT)
						mario.setStatusPlayer(StatusPlayer.UN_MOVE_LEFT);
				}
				// VA CHẠM VỚI VẬT CẢN
				if (pValueX != 0)// || pValueY != 0) 
				{
					
					if (!collidesWith(pX + pValueX * 3, pY + pValueY * 3)) {
						mario.getAnimatedSprite().setPosition( mario.getX() + pValueX * 5,
								mario.getY());
					} 
				}
			}
		});
		
		// Hiệu chỉnh controlSprite =============================================================================
		mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		mDigitalOnScreenControl.getControlBase().setAlpha(0.5f);
		mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128);
		mDigitalOnScreenControl.getControlBase().setScale(1.5f);
		mDigitalOnScreenControl.getControlKnob().setAlpha(0.5f);
		mDigitalOnScreenControl.getControlKnob().setScale(1.f);
		mDigitalOnScreenControl.refreshControlKnobPosition();
		myScene.setChildScene(mDigitalOnScreenControl);

		 /*==============================================================================================================*\
		||============================================|| VÒNG LẶP CỦA GAME ||=============================================||
		 \*==============================================================================================================*/
		
		BOTTOM_Y = mario.getY();// LẤY TOẠ ĐỘ Y MARIO 
		myScene.registerUpdateHandler(new IUpdateHandler() 
		{
			public void onUpdate(float pSecondsElapsed) 
			{
				TIME -= 1;
				time_text.setText(String.valueOf(TIME));
				if (!OVERGAME)
				{
					if (!WIN)
					{
						try{
							Thread.sleep(10);
							for (int i = 0; i < (int)COUNT_ENEMY; i++)
							{
								// ENEMY DI CHUYỂN NGẪU NHIÊN =========================================================
								if (arr_enemy[i].enemy_AnimatedSprite.isVisible())
									arr_enemy[i].moveRandom(1);
								
								// VA CHẠM QUÁI, MARIO DIE ============================================================
								if (mario.collision(arr_enemy[i].enemy_AnimatedSprite) && arr_enemy[i].enemy_AnimatedSprite.isVisible()){
									if (mario.getStatusMario() == StatusPlayer.MOVE_LEFT){
										mario.setStatusPlayer(StatusPlayer.DIE_LEFT);
									}
									else if (mario.getStatusMario() == StatusPlayer.MOVE_RIGHT && arr_enemy[i].enemy_AnimatedSprite.isVisible()){
										mario.setStatusPlayer(StatusPlayer.DIE_RIGHT);
									}
									
									// PHÁT ÂM THANH HIỆU ỨNG...
									if (ControlStatic.SOUND)
										sound_ResetPlayer.Play();
									mario.getAnimatedSprite().setPosition(50, 284);
									mario.setHeart(mario.getHeart() - 1);
									heart_text.setText(String.valueOf(mario.getHeart()));
								}
								
								// VA CHẠM DIỆT QUÁI =========================================================================
								if (mario.collisionKill(arr_enemy[i].enemy_AnimatedSprite) && arr_enemy[i].enemy_AnimatedSprite.isVisible()){
									
									//PHÁT NHẠC...
									if (ControlStatic.SOUND)
										sound_EnemyDie.Play();
									arr_enemy[i].enemy_AnimatedSprite.setVisible(false);
									SCORE += 10;
									score_text.setText(String.valueOf(SCORE));
								}
							}
							
							// VA CHẠM COIN =========================================================================
							for (int i = 0; i < (int)COUNT_COIN; i++){
								if (mario.collision(arr_coin[i].getSprite()) && arr_coin[i].getSprite().isVisible()){
									
									//PHÁT ÂM THANH HIỆU ỨNG...
									if (ControlStatic.SOUND)
										sound_GetCoin.Play();
									arr_coin[i].getSprite().setVisible(false);
									SCORE += 5;
									score_text.setText(String.valueOf(SCORE));
								}
									
							}
							
							// ĂN NẤM ================================================================================
							for (int i = 0; i < (int)COUNT_MUSHROOM; i++) {
								if (mario.collision(arr_mushroom[i].getAnimatedSprite()) && arr_mushroom[i].getAnimatedSprite().isVisible()){
									
									//PHÁT ÂM THANH HIỆU ỨNG...
									if (ControlStatic.SOUND)
										sound_GetCoin.Play();
									arr_mushroom[i].getAnimatedSprite().setVisible(false); 
									mario.setHeart(mario.getHeart() + 1);
									heart_text.setText(String.valueOf(mario.getHeart()));
								}
							}
							
							// RƠI XUỐNG HỐ SÂU =======================================================================
							if (collidesWithHosau(mario.getX() + mario.getWidth() / 2, mario.getY() + mario.getHeight() + 3)) {
								
								//PHÁT ÂM THANH HIỆU ỨNG...
								if (ControlStatic.SOUND)
									sound_ResetPlayer.Play();
								mario.getAnimatedSprite().setPosition(50, 284);
								mario.setHeart(mario.getHeart() - 1);
								heart_text.setText(String.valueOf(mario.getHeart()));
							}
							
							// CHẠM VÀO CỜ ĐÍCH ========================================================================
							if (collidesWithFlag(mario.getX(), mario.getY())) {
								
								WIN = true;
							}
							
							// HẾT THỜI GIAN HOẶC HẾT MẠNG CHƠI ========================================================
							if (mario.getHeart() <= 0 || TIME < 0){
								OVERGAME = true;
							}
							
						}
						catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					else{
						//================
						//QUA MÀNG MỚI
						//HIỂN THỊ ĐIỂM
						//================
						nextLevel();
						
					}
				}
				else{
					//==================================================================
					//GAMEOVER
					//KIỂM TRA ĐIỂM CỦA NGƯỜI CHƠI SAO CÓ LỚN HƠN NGƯỜI CHƠI TRƯỚC KHÔNG
					//NẾU CÓ LƯU VÀO DATABASE
					//==================================================================
					if (db.kt_luu(SCORE)){
						Intent i = new Intent(MainGameActivity.this, Luudiem.class);
						i.putExtra("diem", SCORE);
						MainGameActivity.this.startActivity(i);
						MainGameActivity.this.finish();
					}
					
					//NẾU ĐIỂM THẤP GAMEOVER =======================================================================
					else{
						Intent i = new Intent(MainGameActivity.this, Gameover.class);//CHUYỂN SANG ACTIVITY GAMEOVER
						MainGameActivity.this.startActivity(i);
						MainGameActivity.this.finish();
					}
				}
				
				// NHẢY LÊN CAO =====================================================================================
				if (is_Jump == 1) {
					if (mario.getStatusMario() == StatusPlayer.UN_MOVE_LEFT)
						mario.setStatusPlayer(StatusPlayer.MOVE_UP_LEFT);
					else if (mario.getStatusMario() == StatusPlayer.UN_MOVE_RIGHT)
						mario.setStatusPlayer(StatusPlayer.MOVE_UP_RIGHT);
					if (collidesWith(mario.getX() + mario.getWidth() / 2 + 3, mario.getY() + 3)) {
						is_Jump = 2;
					} else
						mario.getAnimatedSprite().setPosition(mario.getX(), mario.getY() - VEC_Y);
				}

				if (mario.getY() <= (BOTTOM_Y - MAX_HIGH)) {
					is_Jump = 2;
				}

				// RƠI TỪ TRÊN CAO XUỐNG ==============================================================================
				if (is_Jump == 2)
				{
					if (mario.getStatusMario() == StatusPlayer.UN_MOVE_LEFT)
						{
							mario.setStatusPlayer(StatusPlayer.MOVE_UP_LEFT);
						}
					else if (mario.getStatusMario() == StatusPlayer.UN_MOVE_RIGHT)
						mario.setStatusPlayer(StatusPlayer.MOVE_UP_RIGHT);
					mario.getAnimatedSprite().setPosition(mario.getX(), mario.getY() + GRAVITY/2);
				}

				if(mario.getY() > BOTTOM_Y)
					is_Jump = 2;
				
				if (collidesWith(mario.getX() + mario.getWidth() / 2, mario.getY() + mario.getHeight() + 5)) {
					is_Jump = 0;
					BOTTOM_Y = mario.getY();
				}
				else
				{
					mario.getAnimatedSprite().setPosition(mario.getX(), mario.getY() + GRAVITY);
					
				}
			}

			public void reset() {
				// TODO Auto-generated method stub
			}
		});
		myCamera.setHUD(hud);
		return myScene;
	}

	//===============================================|| onLoadComplete Function ||=============================================//
	
	public void onLoadComplete() {
 
	}
	
	//==================================================|| onDestroy Function ||==============================================//
	
	protected void onDestroy() {		
	
		MainGameActivity.this.finish();
		System.out.println("MainGameActivity.this.finish");
		super.onDestroy();
	}

	// HÀM XÉT VA CHẠM VẬT CẢN ========================================================================
	public boolean collidesWith(float pX, float pY){
		TMXTile mTMXTile = VatCanTMXLayer.getTMXTileAt(pX, pY);
    	try{
			if(mTMXTile == null){
				System.out.println("mTMXTile = null"); 
			}
			else{
				TMXProperties<TMXTileProperty> mTMXProperties= mTMXTile.getTMXTileProperties(mTMXTiledMap);
				TMXTileProperty mTMXTileProperty = mTMXProperties.get(0);
				if(mTMXTileProperty.getName().equals("vatcan")){
				}
			}			
			return true;				// CÓ VA CHẠM 
		}catch(Exception e){
			return false;				// KHÔNG VA CHẠM
		}
	}
 
	// HÀM XÉT VA CHẠM CỜ ĐÍCH =========================================================================
	public boolean collidesWithFlag(float pX, float pY){
		TMXTile mTMXTile = FlagTMXLayer.getTMXTileAt(pX, pY);
    	try{
			if(mTMXTile == null){
				System.out.println("mTMXTile = null"); 
			}
			else{
				TMXProperties<TMXTileProperty> mTMXProperties= mTMXTile.getTMXTileProperties(mTMXTiledMap);
				TMXTileProperty mTMXTileProperty = mTMXProperties.get(0);
				if(mTMXTileProperty.getName().equals("flag")){
				}
			}			
			return true;				// CÓ VA CHẠM
		}catch(Exception e){
			return false;				// KHÔNG VA CHẠM
		}
	}
	
	// HÀM XÉT VA CHẠM HỐ SÂU ============================================================================
	public boolean collidesWithHosau(float pX, float pY){
		TMXTile mTMXTile = HosauTMXLayer.getTMXTileAt(pX, pY);
    	try{
			if(mTMXTile == null){
				System.out.println("mTMXTile = null"); 
			}
			else{
				TMXProperties<TMXTileProperty> mTMXProperties= mTMXTile.getTMXTileProperties(mTMXTiledMap);
				TMXTileProperty mTMXTileProperty = mTMXProperties.get(0);
				if(mTMXTileProperty.getName().equals("hosau")){
				}
			}			
			return true;				// CÓ VA CHẠM
		}catch(Exception e){
			return false;				// KHÔNG VA CHẠM
		}
	}

	// HÀM LOAD TÀI KHUYÊN KHÁC ===========================================================================
	public void loadResources() {
		
		// Player =============================================================
		mario = new Player(); 
		mario.onLoadResources(this.mEngine, this);
	 
		 
		// Load enemy, mushroom, coin từ File =================================
		String[] s = getMap(FILE_MAPS);
		String[] s1 = s[0].split(";");
        COUNT_ENEMY = Float.parseFloat(s1[0]);
        COUNT_COIN = Float.parseFloat(s1[1]);
        COUNT_MUSHROOM = Float.parseFloat(s1[2]);
		arr_enemy = new Enemy[(int)COUNT_ENEMY];
		for (int i = 0; i < (int)COUNT_ENEMY; i++){
			arr_enemy[i] = new Enemy();
			arr_enemy[i].onLoadResources(mEngine, this);
		}
		arr_coin = new Coin[(int)COUNT_COIN];
		for (int i = 0; i < (int)COUNT_COIN; i++){
			arr_coin[i] = new Coin();
			arr_coin[i].onLoadResources(mEngine, this);
		}
		arr_mushroom = new Mushroom[(int)COUNT_MUSHROOM];
		for (int i = 0; i < (int)COUNT_MUSHROOM; i++) {
			arr_mushroom[i] = new Mushroom();
			arr_mushroom[i].onLoadResources(mEngine, this);
		}	
		
		// Load Audio ==========================================================
		musicBg = new MusicBg("BackGround.mid");
		sound_ResetPlayer = new SoundEffect("resetplayer.wav");
		sound_EnemyDie = new SoundEffect("EnemyDie.wav");
		sound_GetCoin = new SoundEffect("GetCoin.wav");
		musicBg.onLoadResources(this.mEngine, this);
		sound_ResetPlayer.onLoadResources(mEngine, this);
		sound_EnemyDie.onLoadResources(mEngine, this);
		sound_GetCoin.onLoadResources(mEngine, this);
		
	}

	// HÀM LOAD SCENES ====================================================================================================
	public void loadScenes() {
		 
		// Đặt vị trí Player ===================================================
		mario.setPositionXY(50, 264);
		mario.setHeart(HEART);
		mario.onLoadScene(myScene); 

		
		// Đặt vị trí Enemy, Coin, Mushroom ====================================
		String[] s = getMap(FILE_MAPS);
        int i = 1;
        while (i <= (int)COUNT_ENEMY){
        	String[] str = s[i].split(";");
        	float x = Float.parseFloat(str[0]);
        	float y = Float.parseFloat(str[1]);
        	arr_enemy[i-1].setPositionXY((float)x, (float)y);
        	arr_enemy[i-1].onLoadScene(myScene);
			arr_enemy[i-1].setTMXTiledMap(mTMXTiledMap);
			arr_enemy[i-1].setTMXLayer(VatCanTMXLayer);
			arr_enemy[i-1].setTMXLayer_Enemy(CanEnemyTMXLayer);
        	i++;
        }
        int j = i;
        while (j < i + (int)COUNT_COIN){
        	String[] str = s[j].split(";");
        	float x = Float.parseFloat(str[0]);
        	float y = Float.parseFloat(str[1]);
        	arr_coin[j-i].setPosition(x, y);
        	arr_coin[j-i].onLoadScene(myScene);
        	j++;
        }    
        int k = j;
        while (k < j + (int)COUNT_MUSHROOM) {
			String[] str = s[k].split(";");
			float x = Float.parseFloat(str[0]);
			float y = Float.parseFloat(str[1]);
			arr_mushroom[k-j].setPosition(x, y);
			arr_mushroom[k-j].onLoadScene(myScene);
			k++;
		}
        
        
        // Load MUSIC ============================================================
		if(ControlStatic.SOUND)
		{
			musicBg.Play();
			musicBg.SetVolume(volume);
		}
		
	}
	
	// GET MAPS ========================================================================================================
	public String[] getMap(String filename){
		String chuoi;
		String[] s = null;
		try{
			InputStream in= getAssets().open(filename);
	        int size = in.available();
	        byte[] buffer = new byte[size];
	        in.read(buffer);
	        chuoi= new String(buffer);
	        s = chuoi.split("\n");
	        
	        return s; 
		}catch (Exception ex) {
			//Toast.makeText(this, "Khong the load file map", 3000);
        }
		
		return s;
	}
	
	// NEXT LEVEL =======================================================================================================
	public void nextLevel(){
		Intent next_Level = new Intent(MainGameActivity.this, MainGameActivity.class);
		
		if(LEVEL+1 < ControlStatic.TONG_SO_LEVEL)
			LEVEL++;
		dinhNghiaCacBienThayDoi();
	 
		HEART = mario.getHeart();
		 
		next_Level.putExtra("SCORE", SCORE);
		next_Level.putExtra("HEART", HEART + 1);//TĂNG THÊM 1 MẠNG KHI THÊM LEVEL MỚI
		next_Level.putExtra("LEVEL", LEVEL); 
		next_Level.putExtra("TEN_MAPS", TEN_MAPS + ".tmx");
		next_Level.putExtra("FILE_MAPS", FILE_MAPS);
		next_Level.putExtra("TIME", TIME);
		
    	MainGameActivity.this.startActivity(next_Level);
    	MainGameActivity.this.finish();
	}
	
	// CẬP NHẬT CÁC GIÁ TRỊ THAY ĐỔI =====================================================================================
	public void dinhNghiaCacBienThayDoi(){
		switch(LEVEL){
		case 1:
			
			TEN_MAPS = "maps_" + LEVEL;
			FILE_MAPS = "maps_1.txt";
			TIME = 2500;
			break;
		case 2:
			 
			TEN_MAPS = "maps_" + LEVEL;
			FILE_MAPS = "maps_2.txt";
			TIME = 2500;
			break;
		case 3:
			 
			TEN_MAPS = "maps_" + LEVEL;
			FILE_MAPS = "maps_3.txt";
			TIME = 2500;
			break;
		case 4:
			 
			TEN_MAPS = "maps_" + LEVEL;
			FILE_MAPS = "maps_4.txt";
			TIME = 2500;
			break;
		
		}
	}
	
	//===============================================|| onKeyDown Function ||===============================================//
	
	public boolean onKeyDown(int keycode, KeyEvent event)
	{
		
		if(keycode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN)
		{
			if(mEngine.isRunning())
			{
				mEngine.stop();
				musicBg.Mute();
			}
			else
			{
				mEngine.start();
				musicBg.SetVolume(volume);
			}
		}
		if(keycode == KeyEvent.KEYCODE_MENU && event.getAction() == KeyEvent.ACTION_DOWN)
		{
			Intent menu_action = new Intent(MainGameActivity.this, MenuActivity.class);
			MainGameActivity.this.startActivity(menu_action);
			MainGameActivity.this.finish();
		}
		if(keycode == KeyEvent.KEYCODE_VOLUME_DOWN && event.getAction() == KeyEvent.ACTION_DOWN)
		{
			volume--;
			musicBg.SetVolume(volume);
		}
		else if(keycode == KeyEvent.KEYCODE_VOLUME_UP && event.getAction() == KeyEvent.ACTION_DOWN)
		{
			volume++;
			musicBg.SetVolume(volume);
		}
		
		return false;
	}
								//==============|| The End ||==============\\

}